﻿@page "/systemlog"

@using Gurux.DLMS.AMI.Shared.DIs
@using Gurux.DLMS.AMI.Shared.Enums
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Microsoft.AspNetCore.SignalR.Client
@using Gurux.DLMS.AMI.Shared
@using Gurux.DLMS.AMI.Client.Helpers
@using Gurux.DLMS.AMI.Module

@attribute [Authorize(Roles = "Admin, SystemLogManager")]
@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject ConfirmBase Confirm
@inject IGXNotifier2 Notifier
@implements IDisposable

<PageTitle>@Properties.Resources.SystemLogs</PageTitle>

    <MenuControl RightCorner="true">
        <ChildContent>
            <MenuItem Text="@Properties.Resources.Clear" Icon="oi oi-trash" OnClick="@OnClear" />
        </ChildContent>
    </MenuControl>

    <GXTable @ref="table"
             Context="error"
             ItemsProvider="@GetItems"
             Filter="@Filter"
             OnSearch="@Updated"
             Columns="@Columns"
             ShowAllUsers="false"
             ShowRemoved="false">
        <FilterContent>
            <th>
                <input class="form-control" placeholder="按创建时间..."
                       type="datetime-local"
                       @onchange="@((ChangeEventArgs __e) => filter.CreationTime = @StatusTile.ToDateTime(__e.Value))" />
            </th>
            <th>
                <input class="form-control" type="text" placeholder="@Properties.Resources.FilterByError"
                       @onchange="@((ChangeEventArgs __e) => filter.Message = Convert.ToString(__e.Value))" />
            </th>
            <th>
                <div>
                    <input class="form-control" type="text" placeholder="@Properties.Resources.FilterByLevel"
                           @onchange="@((ChangeEventArgs __e) => filter.Level = @ClientHelpers.LevelToInt(__e.Value))" />
                </div>
            </th>
            <th>
                <input class="form-control" placeholder="按关闭时间..."
                       type="datetime-local"
                       @onchange="@((ChangeEventArgs __e) => filter.Closed = @StatusTile.ToDateTime(__e.Value))" />
            </th>
        </FilterContent>
        <HeaderContent>
            <Th Id="CreationTime" SortMode="SortMode.Descending">@Properties.Resources.CreationTime</Th>
            <Th Id="Message">@Properties.Resources.Error</Th>
            <Th Id="Level">@Properties.Resources.Level</Th>
            <Th Id="Closed">@Properties.Resources.CloseTime</Th>
        </HeaderContent>
        <ItemContent>
            <td>@error.CreationTime</td>
        <td>@error.Message</td>
        <td>@ClientHelpers.LevelToString(error.Level)</td>
        <td>@error.Closed</td>
    </ItemContent>
</GXTable>

<br />
<Confirm @ref="ClearConfirmation"
         ConfirmationChanged="OnClearConfirmation"
         ConfirmationTitle=@Properties.Resources.ConfirmDataClear
         AllowDelete="false"
         OkTitle="@Properties.Resources.Clear"
         ConfirmationMessage="@Properties.Resources.AreYouSureYouWantToClearErrors">
</Confirm>

@code {
    /// <summary>
    /// Action.
    /// </summary>
    [Parameter]
    public string? Action { get; set; }

    /// <summary>
    /// Selected system log ID.
    /// </summary>
    [Parameter]
    public Guid? Id { get; set; }

    /// <inheritdoc />
    public string Name
    {
        get
        {
            return Gurux.DLMS.AMI.Client.Properties.Resources.SystemLogs;
        }
    }

    /// <inheritdoc />
    public Type? ConfigurationUI
    {
        get
        {
            return null;
        }
    }

    /// <inheritdoc />
    public string? Icon
    {
        get
        {
            return "oi oi-tablet";
        }
    }

    /// <summary>
    /// Amount of the sytem logs shown on the view.
    /// </summary>
    [Parameter]
    public int Count { get; set; } = 0;

    /// <summary>
    /// Is filter shown.
    /// </summary>
    [Parameter]
    public bool Filter { get; set; } = true;

    /// <summary>
    /// Available columns.
    /// </summary>
    [Parameter]
    public string[]? Columns { get; set; }

    /// <summary>
    /// Is title shown.
    /// </summary>
    [Parameter]
    public bool Title { get; set; } = true;

    private GXTable<GXSystemLog>? table;

    /// <summary>
    /// System error filter.
    /// </summary>
    private GXSystemLog filter = new GXSystemLog();

    /// <summary>
    /// User is verified before system errors are cleared.
    /// </summary>
    protected ConfirmBase? ClearConfirmation;

    public bool IsActive(GXSystemLog item)
    {
        return item.Closed == null;
    }

    /// <summary>
    /// Closed errors are shown.
    /// </summary>
    public bool ShowClosedErrors { get; set; }

    /// <summary>
    /// Update table.
    /// </summary>
    protected async Task Updated()
    {
        try
        {
            if (table != null)
            {
                await table.RefreshDataAsync(true);
            }
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }

    protected override async Task OnInitializedAsync()
    {
        //Wait until table is loaded. Don't remove this or table is null and last settings are not available.
        await Task.Delay(1);
        try
        {
            if (Notifier == null)
            {
                throw new ArgumentException(Properties.Resources.InvalidNotifier);
            }
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            Notifier.On(this, nameof(IGXHubEvents.ClearSystemLogs), async () =>
            {
                await Updated();
            });
            Notifier.On<IEnumerable<GXSystemLog>>(this, nameof(IGXHubEvents.AddSystemLogs), async (logs) =>
            {
                await Updated();
            });
            Notifier.On<IEnumerable<Guid>>(this, nameof(IGXHubEvents.CloseSystemLogs), async (logs) =>
            {
                await Updated();
            });
            Notifier.Clear();
            Notifier.UpdateButtons();
            if (table != null && Id != null)
            {
                //Get last selected item.
                table.Active = new GXSystemLog() { Id = Id.Value };
            }
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier.ProgressEnd();
        }
    }

    private async ValueTask<ItemsProviderResult<GXSystemLog>> GetItems(GXItemsProviderRequest request)
    {
        //Don't clear status or error is lost.
        Notifier.ProgressStart();
        try
        {
            if (ShowClosedErrors)
            {
                //Show closed errors.
                filter.Closed = DateTimeOffset.MaxValue;
            }
            else
            {
                //Show active errors.
                filter.Closed = null;
            }
            ListSystemLogs req = new ListSystemLogs()
                {
                    Index = request.StartIndex,
                    Count = request.Count,
                    Filter = filter,
                    OrderBy = request.OrderBy,
                    Descending = request.Descending
                };
            if (Count != 0)
            {
                req.Count = Count;
            }
            var ret = await Http.PostAsJson<ListSystemLogsResponse>("api/SystemLog/List", req, request.CancellationToken);
            if (ret.Errors != null)
            {
                //Mark system log as seen.
                await Notifier.Mark(Http, TargetType.SystemLog, ret.Errors.Max(s => s.CreationTime));
            }
            return new ItemsProviderResult<GXSystemLog>(ret.Errors, ret.Count);
        }
        catch (TaskCanceledException)
        {
            //Let the table component handle this.
            throw;
        }
        catch (OperationCanceledException)
        {
            //Might happen when the user scrolls the list rapidly.
        }
        catch (ObjectDisposedException)
        {
            //Might happen when the user scrolls the list rapidly.
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.ToString());
            Notifier.ProcessError(ex);
        }
        finally
        {
            Notifier.ProgressEnd();
        }
        return default;
    }

    public void Dispose()
    {
        Notifier.RemoveListener(this);
    }

    /// <summary>
    /// Clear the system error list.
    /// </summary>

    public void OnClear()
    {
        Notifier?.ClearStatus();
        ClearConfirmation?.Show();
    }

    /// <summary>
    /// Clear the system error list.
    /// </summary>

    public async Task OnClearConfirmation(ConfirmArgs args)
    {
        try
        {
            if (args.Confirm)
            {
                await Http.PostAsJson<ClearSystemLogResponse>("api/SystemLog/Clear", new ClearSystemLog());
            }
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }
}
